package com.stone;

import com.sun.xml.internal.bind.marshaller.NioEscapeHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.udt.UdtChannelOption;

public class Service {

    public static void main(String[] args) {
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);

        //创建workerGroup
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            //创建服务端启动对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //使用链式编程来进行设置
            /**
             *
             * 设置两个线程
             * 使用NioServerSocketChannel作为服务器的通道实现
             * 设置线程队列得到连接个数
             * 设置保持活动的连接状态
             * 创建一个通道测试对象
             */
            bootstrap.group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(UdtChannelOption.SO_BACKLOG, 128)
                    .childOption(UdtChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        /**
                         * 给pipeline设置处理器
                         *
                         * @param socketChannel
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });


            System.out.println("服务器is read...");
            //绑定一个端口并且同步，生成一个channelFutrue对象
            ChannelFuture cf = bootstrap.bind(6668).sync();

            //对关闭通道机进行监听
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
